import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torchvision import models
from torch.utils.data import DataLoader

# 检查CUDA是否可用，并设置device变量
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)

# 数据预处理
transform = transforms.Compose([
    transforms.Resize((224, 224)),  # 将图片统一缩放到224x224
    transforms.ToTensor(),
    transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])

# 加载数据集
train_dataset = torchvision.datasets.ImageFolder(root=r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\lab4_GoogLeNet\data\train', transform=transform)
test_dataset = torchvision.datasets.ImageFolder(root=r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\lab4_GoogLeNet\data\test', transform=transform)

train_loader = DataLoader(dataset=train_dataset, batch_size=2, shuffle=True, pin_memory=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=False, pin_memory=True)

# 加载预训练的GoogLeNet模型
googlenet = models.googlenet(weights=models.GoogLeNet_Weights.IMAGENET1K_V1, aux_logits=True).to(device)

# 修改最后的全连接层以适应三分类任务
googlenet.fc = nn.Linear(googlenet.fc.in_features, 3).to(device)
googlenet.aux1.fc2 = nn.Linear(googlenet.aux1.fc2.in_features, 3).to(device)
googlenet.aux2.fc2 = nn.Linear(googlenet.aux2.fc2.in_features, 3).to(device)

# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(googlenet.parameters(), lr=0.001)

# 初始化用于跟踪最佳模型的变量
best_accuracy = 0.0
num_epochs = 100

# 训练和测试模型
for epoch in range(num_epochs):
    googlenet.train()
    for images, labels in train_loader:
        images = images.to(device)
        labels = labels.to(device)

        outputs, aux1, aux2 = googlenet(images)
        loss1 = criterion(outputs, labels)
        loss2 = criterion(aux1, labels)
        loss3 = criterion(aux2, labels)
        loss = loss1 + 0.3 * loss2 + 0.3 * loss3

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    # 测试模型
    googlenet.eval()
    correct = 0
    total = 0
    with torch.no_grad():
        for images, labels in test_loader:
            images = images.to(device)
            labels = labels.to(device)
            outputs = googlenet(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

        accuracy = 100 * correct / total
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}, Accuracy: {accuracy:.2f}%')

        # 保存最好的模型
        if accuracy >= best_accuracy:
            best_accuracy = accuracy
            torch.save(googlenet.state_dict(), 'googlenet_best_model.pth')
            print("Saved Best Model with Accuracy: {:.2f}%".format(accuracy))
